import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User, LoginForm, LoginResult } from '@/types/user'
import { setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
    const user = ref<User | null>(null)
    const token = ref<string>('')

    const isLoggedIn = computed(() => !!token.value)
    const userRoles = computed(() => user.value?.roles.map(role => role.code) || [])
    const userPermissions = computed(() => user.value?.permissions || [])

    // 登录
    const loginAction = async (loginForm: LoginForm): Promise<void> => {
        try {
            // 模拟登录验证
            if (loginForm.username === 'admin' && loginForm.password === '123456') {
                const mockResult: LoginResult = {
                    token: 'mock-jwt-token-' + Date.now(),
                    user: {
                        id: 1,
                        username: 'admin',
                        email: 'admin@example.com',
                        avatar: '',
                        roles: [{ id: 1, name: '管理员', code: 'admin', permissions: [] }],
                        permissions: ['dashboard:view', 'system:user:view', 'system:user:add', 'system:user:edit', 'system:user:delete', 'system:user:reset', 'system:role:view', 'system:permission:view'],
                        createdAt: '2024-01-01 10:00:00',
                        updatedAt: '2024-01-01 10:00:00'
                    }
                }
                token.value = mockResult.token
                user.value = mockResult.user
                setToken(mockResult.token)
            } else {
                throw new Error('用户名或密码错误')
            }
        } catch (error) {
            throw error
        }
    }

    // 获取用户信息
    const getUserInfoAction = async (): Promise<void> => {
        try {
            // 模拟获取用户信息
            if (user.value) {
                // 如果用户已经存在，直接返回
                return
            }
        } catch (error) {
            throw error
        }
    }

    // 登出
    const logoutAction = async (): Promise<void> => {
        try {
            // 模拟登出，不需要调用API
            console.log('User logged out')
        } catch (error) {
            console.error('Logout error:', error)
        } finally {
            token.value = ''
            user.value = null
            removeToken()
        }
    }

    // 检查权限
    const hasPermission = (permission: string): boolean => {
        return userPermissions.value.includes(permission)
    }

    // 检查角色
    const hasRole = (role: string): boolean => {
        return userRoles.value.includes(role)
    }

    return {
        user,
        token,
        isLoggedIn,
        userRoles,
        userPermissions,
        loginAction,
        getUserInfoAction,
        logoutAction,
        hasPermission,
        hasRole
    }
}) 